import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:amap_location_fluttify/amap_location_fluttify.dart';
import 'package:amap_all_fluttify/amap_all_fluttify.dart';

const COORD_KEY = 'coord_key';

Future<void> main() async {
  runApp(MaterialApp(
    home: App(),
  ));
  await enableFluttifyLog(false);
  await AmapService.init(
    iosKey: 'd6a3fc1340d23613f20c9a4d621d709f',
    androidKey: 'b907cfbcfe78f023b21979523672d349',
  );
}

class App extends StatefulWidget {
  @override
  _AppState createState() => new _AppState();
}

class _AppState extends State<App> {
  Timer _timer;
  List<dynamic> _result = [];

  @override
  void initState() {
    super.initState();
    initLocation();
    initInterval();
  }

  // 初始化定位
  void initLocation() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String json = prefs.getString(COORD_KEY);
    if (json != null) {
      setState(() {
        _result = jsonDecode(json);
      });
    }
    await PermissionHandler().requestPermissions([PermissionGroup.location]);

    // 申请结果
    PermissionStatus permission = await PermissionHandler()
        .checkPermissionStatus(PermissionGroup.location);

    if (permission == PermissionStatus.granted) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  String randomStr() {
    String alphabet = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    int strlenght = 15;

    /// 生成的字符串固定长度
    String left = '';
    for (var i = 0; i < strlenght; i++) {
      left = left + alphabet[Random().nextInt(alphabet.length)];
    }
    return left;
  }

  // 初始化定时任务
  void initInterval() async {
    _timer = Timer.periodic(Duration(seconds: 30), (t) {
      print('==========开始定位===========');
      getLocation();
    });
  }

  void getLocation() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final location = await AmapLocation.fetchLocation();
    print('(${location.latLng.latitude}, ${location.latLng.longitude})');
    print(location.address);
    Map<String, dynamic> _loaction = {
      'latLng': '(${location.latLng.longitude}, ${location.latLng.latitude})',
      'time': '${DateTime.now()}',
      'address': location.address
    };
    setState(() {
      _result.insert(0, _loaction);
    });
    prefs.setString(COORD_KEY, jsonEncode(_result));
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
  }

  /// 设置android端和ios端定位参数
  List<Widget> _renderResult() {
    List<Widget> _widgets = new List<Widget>();
    TextStyle style = TextStyle(fontSize: 16, fontWeight: FontWeight.bold);
    List.generate(_result.length, (index) {
      Map<String, dynamic> _location = _result[index];
      _widgets.add(Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 10.0),
          decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Colors.grey[600]))),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(child: Text('时间：${_location['time']}', style: style)),
              Container(child: Text('地址：${_location['address']}', style: style)),
              Container(child: Text('经纬度：${_location['latLng']}', style: style)),
            ],
          )));
    });
    return _widgets;
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('后台定位定时任务测试'),
            ),
            body: SingleChildScrollView(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: _renderResult(),
            )),
            bottomNavigationBar: BottomAppBar(
                color: Colors.white,
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      FlatButton(
                          onPressed: () async {
                            SharedPreferences prefs =
                                await SharedPreferences.getInstance();
                            prefs.remove(COORD_KEY);
                            setState(() {
                              _result = [];
                            });
                          },
                          child: Text('Clear'),
                          color: Colors.blue,
                          textColor: Colors.white),
                      FlatButton(
                          onPressed: () async {
                            getLocation();
                          },
                          child: Text('获取定位'),
                          color: Colors.blue,
                          textColor: Colors.white),
                    ]))));
  }
}
